import 'package:flutter/material.dart';
import 'package:flutter_ability/flutter_ability.dart';

Future<LoadBalancer> loadBalancer = LoadBalancer.create(4, IsolateRunner.spawn);

class IsolateTextPage extends StatefulWidget {
  const IsolateTextPage({Key? key}) : super(key: key);

  @override
  State<IsolateTextPage> createState() => _IsolateTextPageState();
}

class _IsolateTextPageState extends State<IsolateTextPage> {
  var content = "总和0";

  @override
  void initState() {
    super.initState();
    Log.d(tag: "ISO", "initState()");
  }

  @override
  void dispose() {
    super.dispose();
    Log.d(tag: "ISO", "dispose()");
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Isolate"),
      ),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Padding(
                padding: const EdgeInsets.only(
                    left: 16, right: 16, top: 20, bottom: 20),
                child: TextView.text(content)),
            const SizedBox(
              height: 48,
              width: 48,
              child: CircularProgressIndicator(
                strokeWidth: 2,
                valueColor: AlwaysStoppedAnimation<Color>(YJColors.THEME_COLOR),
              ),
            ),
            const SizedBox(height: 20),
            YJButton(
              onPressed: () {
                int result = sum(200000000);
                content = "总和$result";
                setState(() {});
              },
              text: "计算",
            ),
            YJButton(
              onPressed: () {
                isoSum().then((value) {
                  Log.i(tag: "ISO", "value = $value");
                  content = "总和$value";
                  setState(() {});
                });
              },
              text: "ISO计算",
            )
          ],
        ),
      ),
    );
  }
}

/// 方法调用  loadBalancer.run((argument) => null, null);
Future<int> isoSum() async {
  var lb = await loadBalancer;
  Future<int> res = lb.run<int, int>(sum, 200000000);
  return res;
}

/// 计算0到 num 数值的总和
int sum(int num) {
  int count = 0;
  while (num > 0) {
    count = count + num;
    num--;
  }
  return count;
}
